import React from 'react';
import { ListView, Icon } from 'antd-mobile';
import Router from 'next/router';
import SingleItem from '../singleItem';
import { getRequest } from '../../../tools/requests';
import Swiper from 'swiper/dist/js/swiper.js';
import 'swiper/dist/css/swiper.min.css';
import './index.css';


const NUM_ROWS = 20;
let pageIndex = 0;
let CategoryCount = 0;

function genData(pIndex = 0, navIndex) {
  const dataBlob = {};
  for (let i = 0; i < NUM_ROWS; i++) {
    const ii = (pIndex * NUM_ROWS) + i;
    dataBlob[`${ii}`] = `row - ${navIndex} - ${ii}`;
  }
  return dataBlob;
}


export default class CustomSwipper extends React.Component {
  constructor(props) {
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });

    this.state = {
      dataSource,
      isLoading: true,
      height: 0,
      swiper: null,
      navLists: this.props.navLists.map(item => item.name),
      goodsLists: [],
      currentClass: "",
      noMore: false
    }
  }
  componentDidMount() {
    let _this = this;
    let clickIndex, clickSlide, navSlideWidth, navSum, topBar, bar, 
        startPosition, progress, clientWidth, navWidth;
    //暂时设计每个slide大小需要一致
    let barwidth = 36 //导航粉色条的长度px
    let tSpeed = 300 //切换速度300ms
    const navSwiper = new Swiper('#nav', {
      slidesPerView: 5,
      freeMode: true, 
      on: {
        init: function() {
          navSlideWidth = _this.props.cateId == 3 ? this.slides.eq(0).css('width') : this.slides.eq(0).css('width'); //导航字数需要统一,每个导航宽度一致
          bar = this.$el.find('.bar')
          bar.css('width', navSlideWidth)
          bar.transition(tSpeed)
          navSum = this.slides[this.slides.length - 1].offsetLeft //最后一个slide的位置

          clientWidth = parseInt(this.$wrapperEl.css('width')) //Nav的可视宽度
          navWidth = 0
          for (let i = 0; i < this.slides.length; i++) {
            navWidth += parseInt(this.slides.eq(i).css('width'))
          }

          topBar = this.$el.parents('body').find('#top') //页头

        },

      },  
    });

    const pageSwiper = new Swiper('#page', {
      watchSlidesProgress: true,
      resistanceRatio: 0,
      on: {
        touchMove: function() {
          progress = this.progress
          bar.transition(0)
          bar.transform('translateX(' + navSum * progress + 'px)')
          //红色250,77,71灰色51,51,51
          for (let i = 0; i < this.slides.length; i++) {
            let slideProgress = this.slides[i].progress
            if (Math.abs(slideProgress) < 1) {
              let r = Math.floor((250 - 51) * (1 - Math.pow(Math.abs(slideProgress), 2)) + 51)
              let g = Math.floor((77 - 51) * (1 - Math.pow(Math.abs(slideProgress), 2)) + 51)
              let b = Math.floor((71 - 51) * (1 - Math.pow(Math.abs(slideProgress), 2)) + 51)
              navSwiper.slides.eq(i).find('span').css('color', 'rgba(' + r + ',' + g + ',' + b + ',1)')
            }
          }
        },
        transitionStart: function() {
          let activeIndex = this.activeIndex
          let activeSlidePosition = navSwiper.slides[activeIndex].offsetLeft
          //释放时导航粉色条移动过渡
          bar.transition(tSpeed)
          bar.transform('translateX(' + activeSlidePosition + 'px)')
          //释放时文字变色过渡
          navSwiper.slides.eq(activeIndex).find('span').transition(tSpeed)
          navSwiper.slides.eq(activeIndex).find('span').css('color', 'rgba(250,77,71,1)')
          if (activeIndex > 0) {
            navSwiper.slides.eq(activeIndex - 1).find('span').transition(tSpeed)
            navSwiper.slides.eq(activeIndex - 1).find('span').css('color', 'rgba(51,51,51,1)')
          }
          if (activeIndex < this.slides.length) {
            navSwiper.slides.eq(activeIndex + 1).find('span').transition(tSpeed)
            navSwiper.slides.eq(activeIndex + 1).find('span').css('color', 'rgba(51,51,51,1)')
          }
          //导航居中
          let navActiveSlideLeft = navSwiper.slides[activeIndex].offsetLeft //activeSlide距左边的距离

          navSwiper.setTransition(tSpeed)
          if (navActiveSlideLeft < (clientWidth - parseInt(navSlideWidth)) / 2) {
            navSwiper.setTranslate(0)
          } else if (navActiveSlideLeft > navWidth - (parseInt(navSlideWidth) + clientWidth) / 2) {
            navSwiper.setTranslate(clientWidth - navWidth)
          } else {
            navSwiper.setTranslate((clientWidth - parseInt(navSlideWidth)) / 2 - navActiveSlideLeft)
          }

        },
        transitionEnd: function(){
          // 异步获取数据
          // const navIndex = _this.state.navLists.indexOf(_this.state.currentClass);
          // CategoryCount = navIndex;
          // _this.rData = genData(1, navIndex);
          // _this.setState({
          //   currentClass: _this.state.navLists[this.activeIndex]
          // }, () => {
          //   _this.getGoodsLists(1);
          // })
        }
      }
    })

    this.setState({
      navSwiper,
      pageSwiper
    })

    navSwiper.$el.on('touchstart', function(e) {
      e.preventDefault() //去掉按压阴影
    })
    navSwiper.on('tap', function(e) {
      clickIndex = this.clickedIndex;
      clickSlide = this.slides.eq(clickIndex);
      pageSwiper.slideTo(clickIndex, 0);
      CategoryCount = clickIndex;
      this.slides.find('span').css('color', 'rgba(51,51,51,1)');
      clickSlide.find('span').css('color', 'rgba(250,77,71,1)');
      // const navIndex = _this.state.navLists.indexOf(_this.state.currentClass);
      // _this.rData = genData(1, navIndex);
      // _this.setState({
      //   currentClass: _this.state.navLists[clickIndex]
      // }, () => {
      //   _this.getGoodsLists(1);
      // })
    })
    navSwiper.on('tap', () => {
      const navIndex = this.state.navLists.indexOf(this.state.currentClass);
      this.rData = genData(1, navIndex);
      this.setState({
        currentClass: this.state.navLists[CategoryCount]
      }, () => {
        this.getGoodsLists(1);
      })
    })


    document.body.setAttribute('ontouchstart', '')
    const docHeight = document.documentElement.clientHeight;
    const navIndex = this.state.navLists.indexOf(this.state.currentClass)
    this.rData = genData(1, navIndex);
    this.setState({
      currentClass: this.state.navLists[CategoryCount]
    }, () => {
      this.getGoodsLists(1).then(() => {
        this.setState({
          // dataSource: this.state.dataSource.cloneWithRows(this.rData),
          // isLoading: false,
          height: docHeight - 80,
          // goodsLists: this.state.goodsLists
        });
        pageSwiper.slideTo(CategoryCount, 0);
        navSwiper.slides.find('span').css('color', 'rgba(51,51,51,1)');
        navSwiper.slides.eq(CategoryCount).find('span').css('color', 'rgba(250,77,71,1)');
      });
    })

    if (window.categoryCount) pageSwiper.slideTo(window.categoryCount, 0);
  }

  async onEndReached(event) {
		if (this.state.noMore) {
      return false;
    }
    this.setState({ isLoading: true });
    let pageAdd = ++pageIndex;
		pageAdd == 1 && (pageAdd = 2);
    const result = await getRequest('goods_list/', {page: pageAdd, page_size: NUM_ROWS, topcate: this.props.cateName, subcate: this.state.currentClass});
    if (result.data) {
      const navIndex = this.state.navLists.indexOf(this.state.currentClass);
      CategoryCount = navIndex;
      this.rData = { ...this.rData, ...genData(pageAdd, navIndex) };
      this.setState({
        goodsLists: result.data,
        dataSource: this.state.dataSource.cloneWithRows(this.rData),
        isLoading: false,
      });
    }else {
      this.setState({
        isLoading: false,
        goodsLists: [],
        noMore: true
      })
      Toast.fail(result.msg, 1);
    }
  }

  // 异步获取数据
  async getGoodsLists(pageIndex) {
    const result = await getRequest('goods_list/', {page: pageIndex, page_size: NUM_ROWS, topcate: this.props.cateName, subcate: this.state.currentClass})
    if (result && result.data) {
      const navIndex = this.state.navLists.indexOf(this.state.currentClass)
      this.rData = genData(1, navIndex);
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(this.rData),
        isLoading: false,
        goodsLists: result.data,
      });
    }
  }
  render() {
    const row = (rowData, sectionID, rowID) => {
      let indexID = rowID > 20 ? rowID % 20 === 0 ? 19 : (rowID % 20) - 1 : rowID;
      let objItem = this.state.goodsLists[indexID] ? (
        <SingleItem key={rowID} item={this.state.goodsLists[indexID]}></SingleItem>
      ) : null;
      return objItem
    };

    const navRender = this.state.navLists.map((nav, index) => (
      <div className="swiper-slide" key={index}>
        <span style={{color: index === 0 ? 'rgba(250,77,71,1)' : 'inhret'}}>{ nav }</span>
      </div>
    ))
    const pageRender = this.state.navLists.map( page => (
      <div className="swiper-slide slidepage" key={page}>
        <div className="swiper-container">
          <div className="swiper-wrapper">
            <div className="swiper-slide slidescroll">
              <ListView
                ref={el => this.lv = el}
                dataSource={this.state.dataSource}
                renderFooter={() => (
                  <div style={{ padding: 10, textAlign: 'center' }}>
                    {this.state.isLoading ? <Icon type="loading" /> : '已经到最底部了...'}
                  </div>
                )}
                style={{
                  height: this.state.height,
                  overflow: 'auto',
                  marginTop: '35px'
                }}
                renderRow={row}
                pageSize={NUM_ROWS}
                onScroll={() => { console.log('scroll'); }}
                scrollRenderAheadDistance={500}
                onEndReached={this.onEndReached.bind(this)}
                onEndReachedThreshold={10}
              />
            </div>
          </div>
        </div>
      </div>
    ))
    return (
      <div>
        <div id="top">
          <div className="swiper-container" id="nav">
            <div className="swiper-wrapper">
              { navRender }
              <div className="bar">
                <div className="color"></div>
              </div>
            </div>
          </div>
        </div>
        
        <div className="swiper-container" id="page">
          <div className="swiper-wrapper">
            { pageRender }
          </div>
        </div>
      </div>
    )
  }
}

const handleChangeUrl = (url) => {
  const reg = /^\/details/;
  const regCate = /^\/categories/;
	if (reg.test(url)) {
		window.categoryCount = CategoryCount;
	} else if(regCate.test(url)) {
		return
	} else {
		window.categoryCount = 0;
  }
}

Router.events.on('routeChangeStart', handleChangeUrl)